//
//  BCUserConfigViewController.m
//  BCVersion
//
//  Created by 吴 崧 on 14-2-25.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCUserConfigViewController.h"

#define Push_tag 1
#define New_tag 2
#define Sound_tag 3
#define Vibrator_tag 4
#define Passport_tag 15
#define WorkArea_tag 16

static int flag = 0;

#import <SDWebImage/UIImageView+WebCache.h>
@interface BCUserConfigViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UISwitch *canPushSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *canRecieveNewSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *canSoundSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *canVibratorSwitch;


//@property (nonatomic,strong)ClientUserModel *user;
@end

@implementation BCUserConfigViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

#pragma mark -- Life cycle
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    self.avatarImageView.userInteractionEnabled = YES;
    [self.avatarImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateAvatar:)]];
    [self refreshUI];
    // Do any additional setup after loading the view from its nib.
}




-(void)viewWillAppear:(BOOL)animated
{
    if ([USER_MANAGER.name isEqualToString:EMPTY_STRING]) {
        [self refreshUI];
        
    }else
    {
        [self loadInfoFromLocal];
    }
    [self setSwithStatus];
}

-(void)loadInfoFromLocal
{
    [self.nameBtn setTitle:USER_MANAGER.name forState:UIControlStateNormal];
    [self.placeBtn setTitle:USER_MANAGER.city forState:UIControlStateNormal];
    [self.avatarImageView setImageWithURL:[NSURL URLWithString:USER_MANAGER.avatar] placeholderImage:[UIImage imageNamed:@"userAvatar_placeholder"]];
}


-(void)refreshUI
{
    __weak typeof(self) weakSelf = self;
    [BCNetworkClient userInfo:USER_MANAGER.uid
                         type:@"detail"
                      success:^(NSDictionary *info) {
                          UserModel *model = [[UserModel alloc]initWithDataSource:info];
                          [USER_MANAGER configWithModel:model];
                          model = nil;
                          flag = 1;
                          [weakSelf.avatarImageView setImageWithURL:[NSURL URLWithString:USER_MANAGER.avatar] placeholderImage:[UIImage imageNamed:@"userAvatar_placeholder"]];
                          [weakSelf.nameBtn setTitle:USER_MANAGER.name forState:UIControlStateNormal];
                          [weakSelf.placeBtn setTitle:USER_MANAGER.city forState:UIControlStateNormal];
                      } failure:^(NSError *error) {
                          [weakSelf.avatarImageView setImageWithURL:[NSURL URLWithString:USER_MANAGER.avatar] placeholderImage:[UIImage imageNamed:@"userAvatar_placeholder"]];
                          [weakSelf.nameBtn setTitle:USER_MANAGER.name forState:UIControlStateNormal];
                          [weakSelf.placeBtn setTitle:USER_MANAGER.city forState:UIControlStateNormal];
                      }];
}

-(void)updateAvatar:(UIImageView *)sender
{
    //take the photo
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"相册", nil];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    if (buttonIndex == actionSheet.destructiveButtonIndex) {
        //take photo
        sourceType = UIImagePickerControllerSourceTypeCamera;
    } else if (buttonIndex == actionSheet.firstOtherButtonIndex) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        return;
    }
    
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    
    picker.allowsEditing = YES;
    
    picker.sourceType = sourceType;
    
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

extern const CFStringRef kUTTypeImage;

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
        == kCFCompareEqualTo) {
        
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }
        
        NSData* dateToUpload = UIImageJPEGRepresentation(imageToSave, 0.5f);
        
        [BCProgressHUD showWithTile:@"正在上传头像" animated:YES];
        
        [BCNetworkClient uploadAvatar:USER_MANAGER.auth
                            imageData:dateToUpload
                              success:^(NSString *avatarUrl, NSString *tAvatar) {
                                  
                                  [BCProgressHUD hideAnimated:YES];
                                  [self dismissViewControllerAnimated:YES completion:^{
                                      //reload avatar
                                      USER_MANAGER.avatar = avatarUrl;
                                      [USER_MANAGER save];
                                      [self.avatarImageView setImageWithURL:[NSURL URLWithString:USER_MANAGER.avatar] placeholderImage:[UIImage imageNamed:@"userAvatar_placeholder"]];
                                  }];
                                  
                              } failure:^(NSError *error) {
                                  [BCProgressHUD hideWithError:error animated:YES];
                                  
                              }];
        
        

    } else {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
    
}

-(void)setSwithStatus
{
    self.canPushSwitch.on = USER_MANAGER.canPush;
    self.canRecieveNewSwitch.on = USER_MANAGER.canAlert;
    self.canSoundSwitch.on = USER_MANAGER.canSound;
    self.canVibratorSwitch.on = USER_MANAGER.canVibrator;
}


- (IBAction)updateUserInfo:(UIButton *)sender {
    __block NSInteger tag = sender.tag;
    __weak typeof(self) weakSel = self;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:tag == Passport_tag?@"昵称":@"常住地"
	                                                message:tag == Passport_tag?@"请输入昵称":@"请输入常住地"
	                                               delegate:nil
	                                      cancelButtonTitle:@"取消"
	                                      otherButtonTitles:@"确定",nil];
    
    
	alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    
	alert.shouldEnableFirstOtherButtonBlock = ^BOOL (UIAlertView *alertView) {
		return (BOOL)[alertView textFieldAtIndex : 0].text.length > 0;
	};
    
	alert.tapBlock = ^(UIAlertView *alertView, NSInteger buttonIndex) {
		if (buttonIndex == 1) {
            if (tag == Passport_tag) {
                __block  NSString *name = [alertView textFieldAtIndex:0].text;
                [BCNetworkClient editUsername:@"edit"
                                         auth:USER_MANAGER.auth
                                     username:name
                                         city:weakSel.nameBtn.titleLabel.text
                                      success:^{
                                          [weakSel.nameBtn setTitle:name forState:UIControlStateNormal];
                                          USER_MANAGER.name = name;
                                          [USER_MANAGER save];
                                          
                                      } failure:^(NSError *error) {
                                          
                                          
                                          
                                      }];
            }else
            {
                __block  NSString *city = [alertView textFieldAtIndex:0].text;
                NSLog(@"%@",USER_MANAGER.auth);
                [BCNetworkClient editUsername:@"edit"
                                         auth:USER_MANAGER.auth
                                     username:weakSel.nameBtn.titleLabel.text
                                         city:city
                                      success:^{
                                          [weakSel.placeBtn setTitle:city forState:UIControlStateNormal];
                                          USER_MANAGER.city = city;
                                          [USER_MANAGER save];
                                          
                                      } failure:^(NSError *error) {
                                          
                                      }];
                
            }
            
		}
	};
	[alert show];
}

- (IBAction)about:(UIButton *)sender {
    [BCProgressHUD showWithTile:@"加载中" animated:YES];
    [BCNetworkClient aboutUsSuccess:^(NSString *message) {
        [BCProgressHUD hideAnimated:YES];
        ExhibitionView *ex = [[ExhibitionView alloc]initWithString:message];
        [ex Show];
    } failure:^(NSError *error) {
        [BCProgressHUD hideWithError:error animated:YES];
    }];
}


//
#pragma mark --Custom IB Method


- (IBAction)logOut:(id)sender {
    USER_MANAGER.auth = nil;
    flag = 0;
    [self.tabBarController setSelectedViewController:[self.tabBarController.viewControllers firstObject]];
}

- (IBAction)switchChanged:(UISwitch *)sender {
    switch (sender.tag) {
        case Push_tag:
            USER_MANAGER.canPush = sender.on;
            break;
        case New_tag:
            USER_MANAGER.canAlert = sender.on;
            break;
        case Sound_tag:
            USER_MANAGER.canSound = sender.on;
            break;
        default:
            USER_MANAGER.canVibrator = sender.on;
            break;
    }
    [USER_MANAGER save];
}







@end
